package com.cloudspace.jindun.websocket;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.cloudspace.jindun.JindunApp;
import com.cloudspace.jindun.log.APPLog;
import com.cloudspace.jindun.model.ChannelMemberStatus;
import com.cloudspace.jindun.utils.AppPreferences;
import com.cloudspace.jindun.utils.AppUtil;
import com.cloudspace.jindun.utils.AsyncHandler;
import com.google.gson.JsonObject;

import org.json.JSONObject;

import java.io.Serializable;

import static com.cloudspace.jindun.constants.Constants.GROUP_CHAT_MESSAGE_READ_NUMBER;
import static com.cloudspace.jindun.websocket.WebSocketMessageController.WSHandler.COMMAND_TYPE_CHANGEMIC;
import static com.cloudspace.jindun.websocket.WebSocketMessageController.WSHandler.COMMAND_TYPE_MICINFO;
import static com.cloudspace.jindun.websocket.WebSocketMessageController.WSHandler.COMMAND_TYPE_MIC_USER_IN;
import static com.cloudspace.jindun.websocket.WebSocketMessageController.WSHandler.COMMAND_TYPE_MIC_USER_OUT;
import static com.cloudspace.jindun.websocket.WebSocketMessageController.WSHandler.COMMAND_TYPE_NOTICE_READ;

/**
 * Created by zengxianhua on 17/1/24.
 */

public  class WebSocketMessageController {
    public static final String TAG = WebSocketMessageController.class.getSimpleName();

    private WebSocketMessageController() {

    }

    public void setListener(WebSocketManager.IWebSocketListener l) {
        WebSocketManager.getInsatance().setListener(l);
    }

    public static class ChangeMicMessage implements Serializable{
        public String userId;
        public String type;
        public String channelId;
    }

    public static class MicInfoMessage implements Serializable{
        public String userId;
        public String type; //"come,live"
        public String time;
    }

    public static class MicUserInMessage implements Serializable{
        public String type; //"userin"
        public ChannelMemberStatus member;
    }

    public static class MicUserOutMessage implements Serializable{
        public String type; //"userout"
        public ChannelMemberStatus member;
    }


    public static class NoticeReadMessage implements Serializable{
        public String notificationId;  // 通知id
        public String sentUserId;  // 发送人id
        public String groupId;   // 组id
        public int total;      // 查看人总数
        public String type;
    }


    private String getParamEncrypt(String userId, String channelId) {
        String appendParam = "";
        appendParam += "userId=" + userId;
        appendParam += "&version=" + AppUtil.getAppVersionName();
        appendParam += "&channelId=" + channelId;
        return appendParam;
    }

    public void close(boolean isNeedRelease) {
        if (isNeedRelease) {
            releaseWSHandler();
            releaseListener();
        }
        WebSocketManager.getInsatance().closePing();
        WebSocketManager.getInsatance().closeByUser();
    }

    public void releaseListener() {
        WebSocketManager.getInsatance().releaseListener();
    }

    public void startPing(int ping) {
        WebSocketManager.getInsatance().closePing();
        WebSocketManager.getInsatance().startPing(ping);
    }

    public void releaseWSHandler() {
        mHandler = null;
    }

    public void connect(final String ws) {
        APPLog.zxhLog(TAG + "connect web socket url : " + ws);

        AsyncHandler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    WebSocketManager.getInsatance().connect(ws);
                } catch (Exception e) {
                    APPLog.zxhLog(TAG + " " + Log.getStackTraceString(e));
                }
            }
        });
    }



    private WSHandler mHandler;

    public static class WSHandler extends Handler {
        public static final int COMMAND_TYPE_CHANGEMIC = 0;
        public static final int COMMAND_TYPE_MICINFO = 1;
        public static final int COMMAND_TYPE_MIC_USER_IN = 2;
        public static final int COMMAND_TYPE_MIC_USER_OUT = 3;

        public static final int COMMAND_TYPE_NOTICE_READ = 4;
    }

    //处理服务返回的数据的逻辑---start----

    private <T> T parseModelJson(String message, Class<T> cl) {
        try {
            return JindunApp.getGson().fromJson(message, cl);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public void onReceiveMessage(final String message) {
        //收到 服务器的json串 解析 json通过handler通知消息
        if (mHandler == null) {
            return;
        }

        try {
            JSONObject json = new JSONObject(message);

            String type = json.optString("type");
            APPLog.zxhLog("onReceiveMessage --- > = " + message);

            if (type.equals("changemic")){
                Message msg = mHandler.obtainMessage(COMMAND_TYPE_CHANGEMIC);
                ChangeMicMessage model = parseModelJson(message, ChangeMicMessage.class);
                msg.obj = model;
                mHandler.sendMessage(msg);

                APPLog.zxhLog(TAG + "changemic:" + message);
            }else if (type.equals("update")){
                Message msg = mHandler.obtainMessage(COMMAND_TYPE_MICINFO);
                MicInfoMessage model = parseModelJson(message, MicInfoMessage.class);
                msg.obj = model;
                mHandler.sendMessage(msg);

                APPLog.zxhLog(TAG + "update:" + message);
            }else if (type.equals("userin")){
                Message msg = mHandler.obtainMessage(COMMAND_TYPE_MIC_USER_IN);
                MicUserInMessage model = parseModelJson(message, MicUserInMessage.class);
                msg.obj = model;
                mHandler.sendMessage(msg);

                APPLog.zxhLog(TAG + "userin:" + message);
            }else if (type.equals("userout")){
                Message msg = mHandler.obtainMessage(COMMAND_TYPE_MIC_USER_OUT);
                MicUserOutMessage model = parseModelJson(message, MicUserOutMessage.class);
                msg.obj = model;
                mHandler.sendMessage(msg);

                APPLog.zxhLog(TAG + "userout:" + message);
            }else if (type.equals("notice_read")){
                NoticeReadMessage model = parseModelJson(message, NoticeReadMessage.class);
                APPLog.zxhLog(TAG + "notice_read:" + message);

                String key = String.format("%s_%s_%s", GROUP_CHAT_MESSAGE_READ_NUMBER, model.notificationId,model.groupId);
                APPLog.zxhLog(TAG + "notice_read key " + key);
                AppPreferences.putInt(key, model.total);

                Message msg = mHandler.obtainMessage(COMMAND_TYPE_NOTICE_READ);
                msg.obj = model;
                mHandler.sendMessage(msg);
            }
        }catch (Exception e){
            APPLog.zxhLog(TAG + "onReceiveMessage error:" + Log.getStackTraceString(e));
        }
    }

    public void setWSHandler(WSHandler h) {
        mHandler = h;
    }

    public void sendTextMessage(String msg, String type) {
        //统计
        JsonObject json = new JsonObject();
        json.addProperty("msgbody", msg);
        json.addProperty("type", type);
        WebSocketManager.getInsatance().sendTextMessage(json.toString());
    }


    public static WebSocketMessageController getInstance() {
        return mInstance;
    }

    private static WebSocketMessageController mInstance = new WebSocketMessageController();

}
